//
//  KVNMediaViewerViewController.m
//  Test1
//
//  Created by KelvinYeung on 15/8/11.
//  Copyright (c) 2015年 KelvinYeung. All rights reserved.
//

#import "KVNMediaViewerViewController.h"
#define MEDIA_VIDEO_URLS 0
#define MEDIA_FLOOR_PLANURLS 1
#define MEDIA_RENDERING_URLS 2
#define MEDIA_MODEL_MAP_URLS 3
#define MEDIA_FORMAT_FIGURE_URLS 4
#define MEDIA_TRAFFIC_MAP_URLS 5
#define MEDIA_REAL_MAP_URLS 6
#define MEDIA_OPEN_HOUSE_URLS 7
#define MEDIA_PROJECT_SITE_URLS 8
#define MEDIA_SUPPORTING_MAP_URLS 9
#define MEDIA_PROMOTIONAL_MATERIALS_URLS 10
#define MEDIA_ACTIVITY_DIAGRAM_URLS 11
#define MEDIA_PANORAMA_360_URLS 12



#define KVN_COLLECTION_VIEW_MAIN 0


@interface KVNMediaViewerViewController ()
@property CGFloat segmentItemWidth;
@property UILabel *sectionLabel;
@property int totalCount;

@end

@implementation KVNMediaViewerViewController
@synthesize pagingControlSegment;


- (void)viewDidLoad {
    
    [super viewDidLoad];
    //初始化数据
    [self initDataKeyNameDictionary];
    [self proccessData];

    _orignNavigationBarTintColor =self.navigationController.navigationBar.barTintColor;
    
    self.automaticallyAdjustsScrollViewInsets = YES;
    [self.view setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin];
    self.view.backgroundColor = [UIColor purpleColor];
    CGRect appFrame = [[UIScreen mainScreen] bounds];
    
    //图集-----------------
    UICollectionViewFlowLayout *collectionLayout = [[UICollectionViewFlowLayout alloc] init];
    //单元格大小
    collectionLayout.itemSize =CGSizeMake(appFrame.size.width, appFrame.size.height);
    //行间距
    collectionLayout.minimumLineSpacing = 0;
    //列间距
    collectionLayout.sectionInset = UIEdgeInsetsZero;
    collectionLayout.minimumInteritemSpacing =0;
    [collectionLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    _collectionView  = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, appFrame.size.width, appFrame.size.height) collectionViewLayout:collectionLayout];
    _collectionView.alwaysBounceHorizontal = NO;
    _collectionView.showsHorizontalScrollIndicator = NO;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    //注册cell
    [_collectionView registerClass:[KVNMediaCollectionViewCell class] forCellWithReuseIdentifier:@"KVN_MEDIA_CELL"];
    _collectionView.pagingEnabled = YES;
    _collectionView.tag =KVN_COLLECTION_VIEW_MAIN;
    _collectionView.canCancelContentTouches = NO;
    [self.view addSubview:_collectionView];
    
    
    
    //pageingControl---------------------
    _segmentItemWidth= 60;
    _pagingControl = [[UIScrollView alloc]init];
    _pagingControl.backgroundColor = [UIColor colorWithWhite:0.2 alpha:0.8];
    _pagingControl.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:_pagingControl];
    _pagingControl.frame =CGRectMake(0, appFrame.size.height -45, appFrame.size.width, 45);
    _pagingControl.contentSize = CGSizeMake(_segmentItemWidth*_dataKeyNames.count, 0);
    
    pagingControlSegment = [[UISegmentedControl alloc] initWithItems:_dataKeyNames];
    //pagingControlSegment.frame = CGRectMake(0, 0, _segmentItemWidth*_dataKeyNames.count, 45);
    [_pagingControl addSubview:pagingControlSegment];
    //pagingContrlSegment样式
    pagingControlSegment.segmentedControlStyle = UISegmentedControlStylePlain
    ;
    
    pagingControlSegment.tintColor = [UIColor clearColor];//去掉颜色,现在整个segment都看不见
    NSDictionary* selectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16],
                                             NSForegroundColorAttributeName: [UIColor whiteColor]};
    [pagingControlSegment setTitleTextAttributes:selectedTextAttributes forState:UIControlStateSelected];//设置文字属性
    NSDictionary* unselectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16],NSForegroundColorAttributeName: [UIColor lightTextColor]};
    [pagingControlSegment setTitleTextAttributes:unselectedTextAttributes forState:UIControlStateNormal];
    [pagingControlSegment setSelectedSegmentIndex:0];
    [pagingControlSegment addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    
    
    //sectionLabel----------------
    _sectionLabel = [[UILabel alloc] init];
    _sectionLabel.text = @"实景图";
    _sectionLabel.textColor = [UIColor whiteColor];
    [self.view addSubview:_sectionLabel];
    _sectionLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_sectionLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:0.75 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_sectionLabel attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1 constant:10]];
    _sectionLabel.text = [NSString stringWithFormat:@"%@%d/%ld",
                          [_dataKeyNames objectAtIndex:0]
                          ,1,(unsigned long)[[_data valueForKey:[_dataKeys objectAtIndex:0]] count]];
   
    
    
    //标题
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{UITextAttributeTextColor:[UIColor whiteColor],
       UITextAttributeTextShadowColor:[UIColor whiteColor],
       UITextAttributeTextShadowOffset:[NSValue valueWithUIOffset:UIOffsetMake(0, 0)],
       UITextAttributeFont:[UIFont fontWithName:@"Arial-Bold" size:0.0]
       }];
    
     _totalCount = 0;
    for (NSArray *array in _data.allValues) {
        _totalCount +=  array.count;
    }
    self.navigationItem.title = [NSString stringWithFormat:@"1/%d",_totalCount];
    
    
    //手势
    UITapGestureRecognizer *singleTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];

    singleTapGestureRecognizer.numberOfTouchesRequired = 1; //手指数
    singleTapGestureRecognizer.numberOfTapsRequired = 1; //tap次数
    singleTapGestureRecognizer.delegate = self;
    [singleTapGestureRecognizer setDelaysTouchesBegan:YES];
    [singleTapGestureRecognizer setDelaysTouchesEnded:YES];
    
    [self.view addGestureRecognizer:singleTapGestureRecognizer];
    
    //手势2用来cancel单击事件
    UITapGestureRecognizer *doubleTapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleSingleTap:)];
    doubleTapGestureRecognizer.numberOfTapsRequired = 2;
    doubleTapGestureRecognizer.delegate = self;
    [doubleTapGestureRecognizer setDelaysTouchesBegan:YES];
    [singleTapGestureRecognizer requireGestureRecognizerToFail:doubleTapGestureRecognizer];
    [self.view addGestureRecognizer:doubleTapGestureRecognizer];
    
    
    
    //重设pageControl的contentSize
    [self.view layoutIfNeeded];
    pagingControlSegment.frame =CGRectMake(0, 0, pagingControlSegment.bounds.size.width, 45);
    _pagingControl.contentSize = CGSizeMake(pagingControlSegment.bounds.size.width, 45);
   

    
}


- (void)initDataKeyNameDictionary{

    _dataKeyNameDictionary = @{
                               @"floorPlanUrls":@"平面图"
                               ,@"renderingUrls":@"效果图"
                               ,@"modelMapUrls":@"户型图"
                               ,@"formatFigureUrls":@"业态图"
                               ,@"trafficMapUrls":@"交通图"
                               ,@"realMapUrls":@"实景图"
                               ,@"openHousesUrls":@"样板房图"
                               ,@"projectSiteUrls":@"项目现场"
                               ,@"supportingMapUrls":@"配套图"
                               ,@"promotionalMaterialsUrls":@"推广物料"
                               ,@"activityDiagramUrls":@"活动图"
                               ,@"videoUrls":@"视频"
                               ,@"panorama360Urls":@"360全景"
                               };
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/



#pragma mark --collectionView代理
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

    return [[_data valueForKey:[_dataKeys objectAtIndex:section]]count] ;
    
}



- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
   
    
    KVNMediaCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"KVN_MEDIA_CELL" forIndexPath:indexPath];
    
   // [cell resetImageView];
    if ([[_dataKeys objectAtIndex:indexPath.section] isEqualToString:@"videoUrls"]) {
        [cell setVideoFromURL:[NSURL URLWithString:[[_data valueForKey:@"videoUrls"]objectAtIndex:indexPath.row ]] withDefaultImageFromURL:[NSURL URLWithString:[[_data valueForKey:@"videoDefaultImages"]objectAtIndex:indexPath.row ]]] ;
        //TODO 做特殊处理
    }else{
        [cell setImageFromURL:[NSURL URLWithString:[[_data valueForKey:[_dataKeys objectAtIndex:indexPath.section]]objectAtIndex:indexPath.row ]]];
    };
    
    return cell;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return [_dataKeys count];
    
}


/*
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    UILabel * label = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"COLLECTION_HEADER_VIEW" forIndexPath:indexPath];
    
    return label;
}
*/

#pragma mark --计算data
- (void) proccessData{
    NSMutableArray *keys = [[NSMutableArray alloc] init];
    NSMutableArray *keyNames = [[NSMutableArray alloc] init];
    for (id key in [_data allKeys]) {
        if ([_data valueForKey:key]  != nil
            && [[_data valueForKey:key] count]!=0
            && [_dataKeyNameDictionary valueForKey:key] != nil) {
             //视频排在第一
            if([key isEqualToString:@"videoUrls"]){
                [keys insertObject:key atIndex:0];
                [keyNames insertObject:[_dataKeyNameDictionary valueForKey:key] atIndex:0];
            }else{
                [keys addObject:key];
                [keyNames addObject: [_dataKeyNameDictionary valueForKey:key]];
            }
            
            
        };
    }
   
    
    
    _dataKeys = [NSArray arrayWithArray:keys];
    _dataKeyNames =[NSArray arrayWithArray:keyNames];
    
}


#pragma mark - 滚动停止后改变currentPage的值
- (void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    if (scrollView.tag== KVN_COLLECTION_VIEW_MAIN) {
        

        NSIndexPath *indexPath = [_collectionView indexPathForItemAtPoint:CGPointMake(scrollView.contentOffset.x + scrollView.frame.size.width*0.5, scrollView.frame.size.height*0.5)];
        
        _sectionLabel.text = [NSString stringWithFormat:@"%@%ld/%ld",
                         [_dataKeyNames objectAtIndex:indexPath.section]
                         ,(long)indexPath.item + 1,(unsigned long)[[_data valueForKey:[_dataKeys objectAtIndex:indexPath.section]] count]];
        self.navigationItem.title = [NSString stringWithFormat:@"%d/%d",(int)(scrollView.contentOffset.x/scrollView.frame.size.width )+1,_totalCount];

        [pagingControlSegment setSelectedSegmentIndex:indexPath.section];
    
        //NSLog(@"offset::%f",scrollView.contentOffset.x);
        //NSLog(@"indexPath:section:%ld,item:%ld,row:%ld",(long)indexPath.section,(long)indexPath.item,(long)indexPath.row);
        

    }
}

#pragma mark --segmentAction
-(void)segmentAction:(UISegmentedControl *)Seg{
    
    NSInteger Index = Seg.selectedSegmentIndex;
    [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:Index] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];

    _sectionLabel.text = [NSString stringWithFormat:@"%@%d/%ld",
                          [_dataKeyNames objectAtIndex:Index]
                          ,1,(unsigned long)[[_data valueForKey:[_dataKeys objectAtIndex:Index]] count]];
    self.navigationItem.title = [NSString stringWithFormat:@"1/%d",_totalCount];
}

- (void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBar.barTintColor =[UIColor colorWithWhite:0 alpha:0.8];
}

- (void)viewWillDisappear:(BOOL)animated{
    self.navigationController.navigationBar.barTintColor = _orignNavigationBarTintColor;
    self.navigationController.navigationBar.hidden = NO;
}


#pragma mark --手势操作
- (void) handleSingleTap:(UITapGestureRecognizer *)sender{

    if(sender.numberOfTapsRequired == 1){
    
        [self.navigationController setNavigationBarHidden: !self.navigationController.navigationBar.hidden  animated:YES];
        [UIView animateWithDuration:1 animations:^{
            [self.pagingControl setHidden:!self.pagingControl.hidden];
        }];
    }

}

- (BOOL) gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    return YES;
}




@end

